package com.hivekion.common.services;

import com.hivekion.common.entity.vo.LoginUser;
import com.hivekion.common.security.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service("Permission")
public class PermissionServiceImpl {
      /**
       * 所有权限标识
       */
      private static final String ALL_PERMISSION = "*:*:*";

      /**
       * 管理员角色权限标识
       */
      private static final String SUPER_ADMIN = "admin";

      private static final String ROLE_DELIMETER = ",";

      private static final String PERMISSION_DELIMETER = ",";

      /**
       * 验证用户是否具备某权限
       *
       * @param permission 权限字符串
       * @return 用户是否具备某权限
       */
      public boolean hasPermi(String permission) {
	    if (StringUtils.isEmpty(permission)) {
		  return false;
	    }
	    LoginUser loginUser = SecurityUtils.getCurrentLoginUser(); // 获取当前登录人信息
	    if (loginUser != null && "admin".equals(loginUser.getUsername())) {
		  return true;
	    }
	    if (loginUser == null || CollectionUtils.isEmpty(loginUser.getPermissions())) {
		  return false;
	    }
	    return hasPermissions(loginUser.getPermissions(), permission);
      }

      /**
       * 判断是否包含权限
       *
       * @param permissions 权限列表
       * @param permission  权限字符串
       * @return 用户是否具备某权限
       */
      private boolean hasPermissions(List<String> permissions, String permission) {
	    return permissions.contains(ALL_PERMISSION) || permissions.contains(permission.trim());
      }
}
